<?php
class CommonAction extends BaseAction{
    /**
     * 用户登陆
     */

	public function login($ifAuth=0)
    {
        $accountEnName = D('Account')->where(array('account_id'=>$this->accountId))->getField('account_en_name');
        $this->accountEnName = $accountEnName;
        if (strtolower($accountEnName) == 'hdu' && ($ifAuth!==1 || $this->_get('login_type'))) {//需要注册的进入
        	$this->hdLogin();
        } else {
			session('accountId',$this->accountId);
            parent::login($ifAuth);
        }
    }

    /**
     * 杭电的授权登录
     */
    public function hdLogin()
    {
    	$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    	$redirectUrl = $protocol.$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI];
        $mWechat = D('Wechat/Wechat');
        $wechatInfo = $mWechat->getByAccountId($this->accountId);
        session('wechatId',$wechatInfo['wechat_id']);
        $nickname = '';
        $headimgurl = '';
        //获得微信信息
        if(!session($this->accountId.'_hd_openid')){
        	//dump(session($this->accountId.'_hd_openid'));exit;
        	if(!$this->_get('code')){
        		$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$wechatInfo['appid'].'&redirect_uri='.urlencode($redirectUrl).'&response_type=code&scope=snsapi_userinfo&state=repair#wechat_redirect';
				header('Location:'.$url);	
        		exit;
        	}else{
        		
        		vendor('Wechat.WechatApi');
				$cWechat = new WechatApi($wechatInfo['wechat_id']);
				$info = $cWechat->getUserInfoByAuth($this->_get('code'));
				if($info['status'] != 'S'){
					$this->error('用户信息获取错误，请稍后再试');
				}

				$openId = $info['data']['openid'];

				session($this->accountId.'_hd_openid',$openId);
				$nickname = $info['data']['nickname'];
				$headimgurl = $info['data']['headimgurl'];
				session('headimgurl',$headimgurl);
        	}
        }
        $openId = session($this->accountId.'_hd_openid');

        $wechatUserInfo = M('WechatUser')->getByOpenid($openId);
        //判断微信信息是否存在
        if($wechatUserInfo){
			//杭电需要强制关注(不包括：首页)
			//error_log('accountId:'.$this->accountId.'/sub:'.$wechatUserInfo['subscribe'].'/M='.MODULE_NAME.'/A='.ACTION_NAME,3,'/tmp/hdu.log');
			if ($this->accountId == 25){
				if(!$wechatUserInfo['subscribe'] && MODULE_NAME != 'Center' && ACTION_NAME != 'center'){
					header('Location: ' . U('/base/html/focus'));
					exit;
				}
			}
        	//存在userId,说明已经注册或者认证过了
        	if($wechatUserInfo['user_id']){
	        	$userInfo = D('Base/User')->getByUserId($wechatUserInfo['user_id']);

	        	//待审核跳转
	        	if($userInfo && $userInfo['status'] == 1){
           			$this->hdTips($redirectUrl,2);exit;
	        	}elseif ($userInfo['status'] == 3) { //被禁用显示到原来页面可以编辑
	        		if(!$this->_get('login_type')){
	        			$this->assign('user',$userInfo);
	        			$this->assign('redirectUrl',$redirectUrl);
	        			$this->registerHd();exit;
	        		}
	        		//进去选择身份页
	        		
        		}

	        	//已经有数据直接返回,增加来宾功能
	        	if($userInfo && $userInfo['status'] == 2 && (($userInfo['number'] && $userInfo['type']<2) ||$userInfo['type'] == 2)){
	        		session('userId',$wechatUserInfo['user_id']);
	        		session('staffId',$userInfo['number']);
	        		session('wechatUserId',$wechatUserInfo['wechat_user_id']);
	        		$this->wechatUserId = $wechatUserInfo['wechat_user_id'];
	        		$this->userId = session('userId');
	        		return true;//后面不再执行
	        	}
        	}
        }else{
        	//微信信息入库(user_id数据返回后更新)
        	$wechatCondition = array(
        		'openid'	=>	$openId,
        		'wechat_id' =>	$wechatInfo['wechat_id'],
        		'nickname'	=>	$nickname,
        		'headimgurl'=>  $headimgurl,
        		'create_time'=> time()
        		);
        	$wechatUserInfo = M('WechatUser')->update($wechatCondition);

			//杭电需要强制关注(不包括：首页)
			if ($this->accountId == 25){
				if(!$wechatUserInfo['subscribe'] && MODULE_NAME != 'Center' && ACTION_NAME != 'center'){
					header('Location: ' . U('/base/html/focus'));
					exit;
				}
			}
        }
        session('wechatUserId',$wechatUserInfo['wechat_user_id']);
       	$this->wechatUserId = $wechatUserInfo['wechat_user_id'];//更新user_id时用

       	/**
       	*未注册或者认证的进入选择注册方式页面
       	*/
       	//来宾注册操作页面
       	if($this->_get('login_type') == 3){
       		$this->registerHd();exit;
       	}
       	//来宾登录(选择登录方式)
       	if(!$this->_get('login_type')){
       		$this->assign('redirectUrl',$redirectUrl);
       		$this->selectLogin();exit;
       	}
       
       	//login_type值为1或者2的(即学生或者教师)进入身份认证
       	//请求接口
        if(!session('staffId') || time()-session('tokenTime') > 7*86400 || !session('api_access_token'))
        {
            //返回相应数据
            if($this->_get('accessToken') && $this->_get('tokenTime') && $this->_get('staffId'))
            {
            	//给调全局数据的时候用
                F('api_access_token',$this->_get('accessToken'));
                F('tokenTime',$this->_get('tokenTime'));

            	//判断是否已经被绑定
            	$userInfo = D('User')->getInfo(array('number'=>$this->_get('staffId'),'account_id'=>$this->accountId,'type'=>array('in',array(0,1))));
            	if($userInfo && $userInfo['status'] == 2){
            		$userNum = M('WechatUser')->where(array('user_id'=>$userInfo['user_id'],'openid'=>array('neq',$openId)))->count();
            		if($userNum>0){
            			$this->error('该账号已绑定其他微信号');
            		}
            	}
            	session('api_access_token',$this->_get('accessToken'));
            	session('tokenTime',$this->_get('tokenTime'));
                
                $staffId = $this->_get('staffId');
                session('staffId',$staffId);
            } else {
                $url = "http://wywx.hdu.edu.cn/interface/authApi/auth?openid={$openId}&backUrl=".urlencode($redirectUrl);
                header("Location:$url");
                exit;
            }
        }
        else {
            $staffId = session('staffId');
        }

         //数据入库
         $postData['accountId'] = $this->accountId;
         $postData['sn'] = $staffId;
         $this->sUser = Service('User');
		 $res = $this->sUser->callAouthApi($this->accountEnName, $postData);
		 $this->userId = session('userId');
    }


    /**
    *杭电身份选择页面
    */
    public function selectLogin(){
    	$this->assign('accountId',$this->accountId);
    	$this->display('User:register_select');
    }
    /**
    *杭电来宾注册页面
    */
    public function registerHd(){
    	$this->assign('accountId',$this->accountId);
    	$this->display('User:register_hd');
    }

    /**
    *杭电注册审核提示页面
    */
    public function hdTips($redirectUrl,$type){
    	$this->assign('accountId',$this->accountId);
    	$this->assign('redirectUrl',$redirectUrl);
    	$this->assign('type',$type);
    	$this->display('User:hd_tips');
    }

    //拉取数据
    public function getDormitory(){
        import('ORG.Http');
        $url = 'http://wywx.hdu.edu.cn/interface/authApi/getDormitorys';
        $res = Http::curlPost($url,array('accessToken'=>F('api_access_token')));//如果F('api_access_token')过去需要先去调下身份认证
        dump($res);
    }

    /**
    *杭电宿舍数据同步(先执行getDormitory)
    */
    public function getDormitorys(){
    	import('ORG.Http');
        $url = 'http://wywx.hdu.edu.cn/interface/authApi/getDormitoryData';
        $res = Http::curlPost($url);//
        $result = json_decode($res,true);
        $this->together($result['data']);

    }

     /**
    *杭电数据同步到相应表（可以单独执行，如果中间服务器没数据，先执行getDormitorys方法）
    */
    public function together($list){
    		$accountId = 25;//杭电
            $roomList = M('Room')->where(array('account_id'=>$accountId))->select();
            $codeArr = array();
            foreach($roomList as $value){
                $codeArr[] = $value['room_code'];
            }
            
            $data = array();
            foreach($list as $v){
                //已经存在了则跳过
                if(in_array($v['dor_code'],$codeArr)){
                    continue;
                }

               $communityInfo = M('Community')->where(array('account_id'=>$accountId,'community_name'=>$v['dor_site']))->find();
               if(!$communityInfo){
                  $communityInfo = M('Community')->update(array('account_id'=>$accountId,'community_name'=>$v['dor_site'],'create_time'=>time()));
               }
               //判断楼幢
               $buildingCondition = array('account_id'=>$accountId,'community_id'=>$communityInfo['community_id'],'building_name'=>$v['dor_building']);
                $buildingInfo = M('Building')->where($buildingCondition)->find();
                if(!$buildingInfo){
                    $buildingCondition['create_time'] = time();
                    $buildingInfo = M('Building')->update($buildingCondition);
                }

                //楼层
                $floorCondition = array('account_id'=>$accountId,'building_id'=>$buildingInfo['building_id'],'floor_name'=>$v['dor_floor']);
                $floorInfo = M('Floor')->where($floorCondition)->find();
                if(!$floorInfo){
                    $floorCondition['create_time'] = time();
                    $floorInfo = M('Floor')->update($floorCondition);
                }

                //房间数据
                $infoArr = array(
                    'building_id'   =>  $buildingInfo['building_id'],
                    'floor_id'      =>  $floorInfo['floor_id'],
                    'room_name'     =>  $v['dor_room'],
                    'room_code'     =>  $v['dor_code'],
                    'create_time'   =>  time(),
                    'account_id'	=>	$accountId	
                    );
               
                $data[] = $infoArr;  
                $infoArr = array();
            }     
            $res = M('Room')->addAll($data);  
            echo 'success';
    }


    /**
    *获得杭电组织架构
    */
    public function getUnits(){
    	import('ORG.Http');
        $url = 'http://wywx.hdu.edu.cn/interface/authApi/getUnits';
        $res = Http::curlPost($url);//
        $result = json_decode($res,true);
        if(!$result['data']){
        	return false;
        }
        $accountId = 25;
        foreach($result['data'] as $v){
        	$info = M('Department')->where(array('unitcode'=>$v['UNITCODE']))->find();
        	if(!$info){
        		$data = array(
        			'department_name'	=>	$v['UNITNAME'],
        			'unitcode'			=>	$v['UNITCODE'],
        			'belongunit'		=>	$v['BELONGUNIT'],
        			'account_id'		=>	$accountId,//杭电
        			'create_time'		=>	time()
        			);
        		M('Department')->update($data);
        	}
        }

        //更新parent_id
        $list = M('Department')->where(array('account_id'=>$accountId,'cut_off'=>0,'belongunit'=>array('neq','0'),'parent_id'=>0))->select();
        foreach($list as $vv){
        	$belongInfo = M('Department')->where(array('unitcode'=>$vv['belongunit']))->find();
        	$arr = array(
        		'department_id'	=>	$vv['department_id'],
        		'parent_id'		=>	$belongInfo['department_id']
        		);
        	M('Department')->update($arr);
        }
        echo 'success';
    }

	public function upload(){

		$type=$this->_request('type');
		$origin=$this->_request('origin');
		$cate_id=$this->_request('cate_id');
		$is_thumb=$this->_request('is_thumb')?$this->_request('is_thumb'):0;
		if(!$type){
			$type='image';
		}
		//导入上传类
		$upload = new UploadFile();
		if($type=="image"){
			//设置上传文件大小
			$upload->maxSize = 8*1024*1024;
			//设置上传文件类型
			$upload->allowExts = explode(',', 'jpg,png,jpeg');
		}elseif ($type=="voice"){
			//设置上传文件大小
			$upload->maxSize = 2*1024*1024;
			//设置上传文件类型
			$upload->allowExts = explode(',', 'mp3,amr');
		}elseif ($type=="thumb"){
			//设置上传文件大小
			$upload->maxSize = 64*1024;
			//设置上传文件类型
			$upload->allowExts = explode(',', 'jpg');
		}
		//设置附件上传目录
		$upload->savePath = './uploads/'.$type.'/'.session('accountId').'/';
		//设置上传文件规则
		$upload->saveRule = 'time';
		if ($is_thumb == 1 && $type == 'image') {
			//生成缩略图
			$upload->thumb = true;
			$upload->thumbMaxWidth = '400';// 缩略图最大宽度
			$upload->thumbMaxHeight = '400';// 缩略图最大高度
			$upload->thumbPath = './uploads/' . $type . '/' . session('accountId') . '/';// 缩略图保存路径
		}
		if (!$upload->upload()) {
			//捕获上传异常
			$this->ajaxReturn(array('status'=>'F','message'=>$upload->getErrorMsg()));
		} else {
			//取得成功上传的文件信息
			$uploadList = $upload->getUploadFileInfo();
			$url = C('site_url').'/uploads/'.$type.'/'.session('accountId').'/'.$uploadList[0]['savename'];
			if ($is_thumb == 1 && $type == 'image') {
				$thumb_url = C('site_url') . '/uploads/' . $type . '/' . session('accountId') . '/' . $upload->thumbPrefix . $uploadList[0]['savename'];
			}else{
				$thumb_url = '';
			}
			$this->ajaxReturn(array('status'=>'S','message'=>'上传成功','url'=>$url,'thumb_url'=>$thumb_url));
		}
	}

	/**
	 *获取园区信息
	 */
	public function getCommunityList(){
		$communityId = $this->_post('id');
		if($communityId) {
			$info = D('Community')->getList(array('community_id' => $communityId),'','sort asc');
		}else{
			$info = D('Community')->getList(array('account_id' => session('accountId'),'cut_off' => 0),'','sort asc');
		}
		$this->returnInfo($info);
	}

	/**
	 *获取楼幢信息
	 */
	public function getBuildingList(){
		$communityId = $this->_post('id');
		if($communityId) {
			$info = D('Building')->getList(array('community_id' => $communityId,'cut_off' => 0),'','sort asc');
		}else{
			$info = D('Building')->getList(array('account_id' => session('accountId'),'cut_off' => 0),'','sort asc');
		}
		$this->returnInfo($info);
	}

	/**
	 *获取楼层信息
	 */
	public function getFloorList()
	{
		$buildingId = $this->_post('id');
		if ($buildingId) {
			$info = D('Floor')->getList(array('building_id' => $buildingId, 'cut_off' => 0),'','floor_name asc,sort asc');
		}else{
			$info = D('Floor')->getList(array('account_id' => session('accountId'), 'cut_off' => 0),'','sort asc');
		}
		

		$this->returnInfo($info);
	}

	/**
	 *获取寝室信息
	 */
	public function getRoomList()
	{
		$floorId = $this->_post('id');
		if ($floorId) {
			$info = D('Room')->getList(array('floor_id' => $floorId, 'cut_off' => 0),'','room_name asc');
		}else{
			$info = D('Room')->getList(array('account_id' => session('accountId'), 'cut_off' => 0),'','room_name asc');
		}
		$this->returnInfo($info);
	}

	/**
	 * 获取学院列表
	 */
	public function getCollege(){
		$condition = array(
			'account_id' => $this->accountId,
			'cut_off' => 0,
		);
		$collegeList = M('College')->where($condition)->order('sort asc')->select();
		$this->ajaxReturn(array('status' => 'S', 'data' => $collegeList ? $collegeList : array()));
	}

	/**
	 * 获取年级列表
	 */
	public function getGrade(){
		$collegeId = $this->_post('college_id');
		$condition = array(
			'college_id' => $collegeId,
			'cut_off' => 0,
		);
		$gradeList = M('Grade')->where($condition)->order('sort asc')->select();
		$this->ajaxReturn(array('status' => 'S', 'data' => $gradeList ? $gradeList : array()));
	}

	/**
	 * 获取专业列表
	 */
	public function getMajor(){
		$gradeId = $this->_post('grade_id');
		$condition = array(
			'grade_id' => $gradeId,
			'cut_off' => 0,
		);
		$majorList = M('Major')->where($condition)->order('sort asc')->select();
		$this->ajaxReturn(array('status' => 'S', 'data' => $majorList ? $majorList : array()));
	}

	/**
	 * 获取班级列表
	 */
	public function getClass(){
		$majorId = $this->_post('major_id');
		// 查询grade_id
		$gradeId = M('Major')->where(array('major_id' => $majorId))->getField('grade_id');
		$condition = array(
			'major_id' => $majorId,
			'grade_id' => $gradeId,
			'cut_off' => 0,
		);
		$classList = M('Class')->where($condition)->order('sort asc')->select();
		$this->ajaxReturn(array('status' => 'S', 'data' => $classList ? $classList : array()));
	}


	/**
	 *ajax返回
	 * @param array $info
	 */
	public function returnInfo($info){
		if($info){
			$this->ajaxReturn(array('status'=>'S', 'data'=> $info));
		}else{
			$this->ajaxReturn(array('status'=>'F', 'data' => null));
		}
	}
	/**
	 * 新功能提醒
	 */
	public function comm(){

		$cookie = $this->g_cookie('comm_uri');
		$path = $this->g_cookie('comm_path');
		$day = time()-86400*7;
		$condition['path'] = strtolower($path);
		$condition['cut_off'] = 0;
		$condition['create_time'] = array('egt',$day);
		$list = D('Features')->where($condition)->select();
		$this->assign('comm_uri',$cookie);
		$this->assign('commdata',$list);
		$this->display();
	}
	/**
	 * 获取cookie
	 */
	public function g_cookie($name){
		$ck = $_COOKIE[$name];
		$cookie =  unserialize($ck);
		return $cookie;
	}
}